from __future__ import absolute_import
import logging
from forest.api import Command
import solv

#from pkgr.pkgr import Pkgr
from forest.resources.packages import PackageInstallList

logger = logging.getLogger('commands.pkgr.install')

class Install(Command):
    __register__ =  'commands.pkgr.Install'

    def run(self, config):
        pkgr = config.get('_pkgr')
        pool = pkgr.get_solv_pool()
        #repos = pkgr.get_configured_repos()

        logger.debug('Installing packages...')

        package_actions = PackageInstallList(config)

        names = []
        for packageaction in package_actions:
            if packageaction.requires_erase():
                continue
            logger.info(packageaction)

            if packageaction.is_group():
                for group in pkgr.get_all_groups():
                    if group.get_id() != packageaction.get_name()[1:]:
                        continue

                    if packageaction.get_group_optional():
                        names.extend(group.get_optional_packages())

                    if packageaction.get_group_default():
                        names.extend(group.get_default_packages())

                    names.extend(group.get_mandatory_packages())
                    logger.info('!!! adding packages, {}'.format(names))
                    break


            else:
                names.append(packageaction.get_name())


        #pkgr.get_cmdline_repo(names)

        pkgr.post_repo_load()
        jobs = pkgr.names_to_jobs('install', names)


        pkgr.set_jobs(jobs)
        for job in jobs:
            job.how |= solv.Job.SOLVER_INSTALL

        solver = None
        while True:
            solver = pool.Solver()
            solver.set_flag(solv.Solver.SOLVER_FLAG_SPLITPROVIDES, 1);
            problems = solver.solve(jobs)

            if not problems:
                break
            pkgr.handle_problems(jobs, problems)

        trans = solver.transaction()
        del solver

        config.set('_txn', trans)
